package com.youhome.service;

import com.youhome.model.WXSession;
import com.youhome.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@Service
@Slf4j
public class TokenService {

    private static final long expiry_date = 30 * 60; //(s) token 有效期 30 分种

    @Autowired
    private RedisService redisService;

    public static void main(String[] args) {
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJ1dWlkIjoiNzc0MzMxNDgtOTM3OC00ZWNmLThjMTUtMTEwMDczMmJkOWMyIn0.qrdSRnnxDDfPYl-shNjXtyzujl43-A5IaeOWse4ElUM";
        if (TokenUtils.isExpired(token)) {
            Map<String, Object> map = TokenUtils.parserToken(token);
            Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = iterator.next();
                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
            }
        } else {
            log.error("Token 已经过期！");
        }
    }

    public boolean checkToken(String token) {
        String tokenRe = (String) redisService.get("token:" + token);
        if (StringUtils.isNotBlank(tokenRe) && token.equals(tokenRe)) {
            return true;
        } else {
            return false;
        }
    }

    public String createToken(WXSession wxSession) {
        log.info("login success" + wxSession.toString());
        Map map = new HashMap<>();
        map.put("openid", wxSession.getOpenid());
        String token = TokenUtils.createToken(map);
        //保存token 到redis
        redisService.set("token:" + token, token, expiry_date);
        //保存 openid 和 session_key 到 redis
        redisService.set("openid:" + wxSession.getOpenid(), wxSession.getSession_key(), expiry_date);
        return token;
    }

    public void cleanToken(String token, String openid) {
        // 从 redis 删除 token
        redisService.remove("token:" + token);
        //从 redis 删除 openid 和 session_key
        redisService.remove("openid:" + openid);
    }
}
